package com.stewiechen.aipet;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

public class ChatMsgItemAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private static final String TAG = "ChatMsgItemAdapter";

    List<ChatMsg> msgList;

    private Context context;

    private RecyclerView parent;

    private final Handler mainHandler = new Handler(Looper.getMainLooper());

    public ChatMsgItemAdapter(Context context, RecyclerView parent) {
        this.context = context;
        this.parent = parent;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view;
        if (viewType == Constant.MessageType.AI_MSG) {
            view = LayoutInflater.from(context).inflate(R.layout.item_chat_msg_ai_layout, parent, false);
        } else {
            view = LayoutInflater.from(context).inflate(R.layout.item_chat_msg_me_layout, parent, false);
        }
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        ChatMsg message = msgList.get(position);
        ViewHolder vh = (ViewHolder) holder;
        vh.msg.setText(message.getMsg());
    }

    @Override
    public int getItemCount() {
        return msgList == null ? 0 : msgList.size();
    }

    @Override
    public int getItemViewType(int position) {
        ChatMsg msg = msgList.get(position);
        return msg.getMsgType();
    }

    public void flushData(List<ChatMsg> messageList) {
        msgList = messageList;
        // mMessageList.sort((o1, o2) -> -Long.compare(o1.getGmtCreate().getTime(), o2.getGmtCreate().getTime()));
        mainHandler.post(new Runnable() {
            @Override
            public void run() {
                notifyDataSetChanged();
                scrollToBottom();
            }
        });
    }

    public void appendData(List<ChatMsg> messageList) {
        if (messageList == null || messageList.isEmpty()) {
            return;
        }
        if (msgList == null || msgList.isEmpty()) {
            flushData(messageList);
            return;
        }

        int size = msgList.size();
        msgList.addAll(messageList);
        // 按时间倒序排序
        // mMessageList.sort((o1, o2) -> -Long.compare(o1.getGmtCreate().getTime(), o2.getGmtCreate().getTime()));
        mainHandler.post(new Runnable() {
            @Override
            public void run() {
                notifyItemRangeChanged(size, msgList.size());
                scrollToBottom();
            }
        });
    }

    public void appendData(ChatMsg message) {
        if (message == null) {
            return;
        }
        if (msgList == null || msgList.isEmpty()) {
            List<ChatMsg> tmp = new ArrayList<>();
            tmp.add(message);
            flushData(tmp);
            return;
        }

        int size = msgList.size();
        msgList.add(message);
        // 按时间倒序排序
        // mMessageList.sort((o1, o2) -> -Long.compare(o1.getGmtCreate().getTime(), o2.getGmtCreate().getTime()));
        mainHandler.post(new Runnable() {
            @Override
            public void run() {
                notifyItemRangeChanged(size, msgList.size());
                scrollToBottom();
            }
        });
    }

    public void updateLastMsg(String content) {
        if (msgList == null || msgList.isEmpty()) {
            ChatMsg chatMsg = new ChatMsg();
            chatMsg.setMsg(content);
            chatMsg.setMsgType(Constant.MessageType.AI_MSG);
            List<ChatMsg> tmp = new ArrayList<>();
            tmp.add(chatMsg);
            flushData(tmp);
            return;
        }
        int lastPosition = msgList.size() - 1;
        ChatMsg lastData = msgList.get(lastPosition);
        lastData.setMsg(content);
        mainHandler.post(new Runnable() {
            @Override
            public void run() {
                notifyItemChanged(lastPosition);
                scrollToBottom();
            }
        });
    }

    void scrollToBottom() {
        LinearLayoutManager layoutManager = (LinearLayoutManager) parent.getLayoutManager();
        if (layoutManager == null) return;
        layoutManager.setStackFromEnd(true);
        layoutManager.setSmoothScrollbarEnabled(true);
        layoutManager.scrollToPositionWithOffset(this.getItemCount() > 0 ? this.getItemCount() - 1 : 0, Integer.MIN_VALUE);
    }

    public List<ChatMsg> getMessageList() {
        return msgList;
    }


    public static class ViewHolder extends RecyclerView.ViewHolder {

        private final TextView msg;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            msg = itemView.findViewById(R.id.msg_content);
            itemView.setTag(this);
        }
    }
}
